package com.yuexiao.config;

import com.yuexiao.service.DetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName:SecurityConfig
 * @Auther: YUEXIAO
 * @Description: 权限配置
 * @Date: 2022/8/13 10:03
 * @Version: v1.0
 */
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationSuccessHandler successHandler;
    @Autowired
    private MyAuthenticationFailureHandler failureHandler;
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    private DetailsService detailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf，开启跨域请求
        http.csrf().disable().cors();

        //设置自定义登录页
        http.formLogin()
                .loginPage("/front/page/login.html")
                .loginProcessingUrl("/user/login")
                .usernameParameter("phone")
                .passwordParameter("code")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .permitAll();

        //设置释放资源
        http.authorizeRequests()
                .antMatchers("/front/images/**","/front/api/**","/front/js/**","/backend/plugins/**","/front/styles/**","/user/login","/user/logout","/user/sendMsg","/doc.html","/webjars/**","/swagger-resources","/v2/api-docs")
                .permitAll();

        //设置权限资源
        http.authorizeRequests()
                .antMatchers("/front/index.html","/front/page/**")
                .access("hasRole('ROLE_NOMAL')").anyRequest().authenticated();

        //设置登出
        http.logout()
                .logoutUrl("/user/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll();

        //支持frame
        http.headers().frameOptions().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(detailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }
}
